package com.topteam.frame.controllor;

import java.util.Date;
import java.util.UUID;

import com.jfinal.plugin.activerecord.Page;
import com.topteam.component.easyui.EasyDataTableModel;
import com.topteam.core.Path;
import com.topteam.frame.entity.FrameMail;
import com.topteam.frame.entity.FrameMailUser;
import com.topteam.security.UserSession;
import com.topteam.utility.StringUtil;

@Path("/framemail")
public class FrameMailController extends BaseController{

	public void newMail(){
		String id  = UUID.randomUUID().toString();
		setAttr("id", id);
		render("/frame/FrameMailNew.html");
	}
	
	public void inbox(){
		render("/frame/FrameMailInbox.html");
	}
	
	public void table(){
		EasyDataTableModel model = new EasyDataTableModel(this) {
			@Override
			public Page<?> fechData(int page, int size) {
				UserSession session = getUserSession();
				return FrameMailUser.dao.getUserMail(session.getUserid(), page, size);
			}
		};
		renderJson(model.toJson());
	}
	
	public void sendmail(){
		String id = getPara("id");
		String title = getPara("title");
		String content = getPara("content");
		String userIds = getPara("userId");
		FrameMail mail = new FrameMail();
		mail.set("id", id);
		mail.set("title", title);
		mail.set("content", content);
		UserSession session = getUserSession();
		mail.set("sendUser", session.getUserid());
		mail.set("sendUserName", session.getDisplayName());
		mail.set("sendTime", new Date());
		mail.set("statue", 1);
		mail.set("mailboxid", "0001");
		mail.save();
		String[] users = userIds.split(",");
		for(String u : users){
			if(StringUtil.isNotNull(u)){
				FrameMailUser mailUser = new FrameMailUser();
				mailUser.set("id", UUID.randomUUID().toString());
				mailUser.set("mailId", id);
				mailUser.set("belongUser", u);
				mailUser.set("type", 1);
				mailUser.save();
			}
		}
		
		renderText("发生成功");
	}
	
	public void readmail(){
		String id = getPara("id");
		UserSession session = getUserSession();
		boolean auth = FrameMailUser.dao.queryAuth(id,session.getUserid());
		if(!auth){
			renderError(404);
			return;
		}
		FrameMail mail = FrameMail.dao.findById(id);
		setAttr("mail", mail);
		render("/frame/FrameMailRead.html");
	}
	
}
